package org.xiaojl.sys.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.xiaojl.common.SessionUser;
import org.xiaojl.common.base.BaseController;
import org.xiaojl.dwz.DwzAjax;
import org.xiaojl.dwz.page.PageBean;
import org.xiaojl.dwz.page.PageParam;
import org.xiaojl.sys.entity.SysRole;
import org.xiaojl.sys.entity.SysUser;
import org.xiaojl.sys.service.SysRoleService;
import org.xiaojl.sys.service.SysUserRoleService;
import org.xiaojl.sys.service.SysUserService;
import org.xiaojl.utils.MybatisPlusPageUtil;
import org.xiaojl.utils.ToolUtil;
import org.xiaojl.utils.WebUtil;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;

/**
 * <p>
 * 系统用户 前端控制器
 * </p>
 *
 * @author xiaojl
 * @since 2017-08-18
 */
@Controller
@RequestMapping("/sys/sysUser")
public class SysUserController extends BaseController{
	private static final Logger log = LoggerFactory.getLogger(SysUserController.class);
	private static final String basePagePath = "sys/user/";
	
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	
//	@RequiresPermissions("pms:role:view")
	@RequestMapping("/list")
	public String List(PageParam pageParam, SysUser user, Model model){
		try {
			String orderBy = "";
			boolean isAsc = true;
			Page<SysUser> page = MybatisPlusPageUtil.getPage(pageParam.getPageNum(), 
					pageParam.getNumPerPage(), orderBy, isAsc);
			
			Page<SysUser> resultPage = null;
			if(ToolUtil.isNotEmpty(user)){
				resultPage = sysUserService.selectPage(page, user.bindingQueryWrapper());
			}else{
				resultPage = sysUserService.selectPage(page);
			}
			
			PageBean<SysUser> pageBean = new PageBean<SysUser>(resultPage.getCurrent(),
					resultPage.getSize(),resultPage.getTotal(),resultPage.getRecords());
			
			model.addAttribute("pageBean", pageBean);
			model.addAttribute("pageParam", pageParam);
			model.addAttribute("user", user);
			
			return basePagePath+"list";
		} catch (Exception e) {
			log.error("查询列表数据出现异常:", e);
			return operateError("获取数据失败", model);
		}
	}
	
	/**
	 * 转到添加页面 .
	 */
//	@RequiresPermissions("pms:role:add")
	@RequestMapping("/addUI")
	public String addUI(Model model) {
		try {
			return basePagePath+"add";
			
		} catch (Exception e) {
			log.error("进入添加页面出现异常:", e);
			return operateError("获取数据失败", model);
		}
	}
	
	/**
	 * 保存 .
	 */
//	@RequiresPermissions("pms:role:add")
	@RequestMapping("/add")
	public String add(Model model, SysUser entity, DwzAjax dwz) {
		try {
			List<SysUser> listByLoginName = sysUserService.selectList(new EntityWrapper<SysUser>().eq("loginName",entity.getLoginName()));
			if (ToolUtil.isNotEmpty(listByLoginName)) {
				return operateError("登录名【" + entity.getLoginName() + "】已存在", model);
			}
			
			List<SysUser> listByRealName = sysUserService.selectList(new EntityWrapper<SysUser>().eq("realName",entity.getRealName()));
			if (ToolUtil.isNotEmpty(listByRealName)) {
				return operateError("真实用户名【" + entity.getRealName() + "】已存在", model);
			}

			entity.setCreateBy(WebUtil.getSessionUser(request).getSysUser().getId());
			sysUserService.insert(entity);
			return operateSuccess(model, dwz);
		} catch (Exception e) {
			log.error("添加数据出现异常:", e);
			return operateError("保存数据失败", model);
		}
	}
	
	/**
	 * 转到修改页面 .
	 */
//	@RequiresPermissions("pms:role:edit")
	@RequestMapping("/editUI")
	public String editUI(Model model, Long id) {
		try {
			SysUser entity = sysUserService.selectById(id);
			if (ToolUtil.isEmpty(entity)) {
				return operateError("获取数据失败", model);
			}

			model.addAttribute("entity",entity);
			return basePagePath+"edit";
		} catch (Exception e) {
			log.error("进入编辑页面时，获取数据出现异常:id="+id, e);
			return operateError("获取数据失败", model);
		}
	}
	
	/**
	 * 保存修改后的信息 .
	 * 
	 */
//	@RequiresPermissions("pms:role:edit")
	@RequestMapping("/edit")
	public String edit(Model model, SysUser entity, DwzAjax dwz) {
		try {
			Long id = entity.getId();

			SysUser sysUser = sysUserService.selectById(id);
			if (ToolUtil.isEmpty(sysUser)) {
				return operateError("无法获取要修改的数据", model);
			}
			
			if(!entity.getLoginName().equals(sysUser.getLoginName())){
				List<SysUser> listByLoginName = sysUserService.selectList(new EntityWrapper<SysUser>().eq("loginName",entity.getLoginName()));
				if (ToolUtil.isNotEmpty(listByLoginName)) {
					return operateError("登录名【" + entity.getLoginName() + "】已存在", model);
				}
			}
			if(!entity.getRealName().equals(sysUser.getRealName())){
				List<SysUser> listByRealName = sysUserService.selectList(new EntityWrapper<SysUser>().eq("realName",entity.getRealName()));
				if (ToolUtil.isNotEmpty(listByRealName)) {
					return operateError("真实用户名【" + entity.getRealName() + "】已存在", model);
				}
			}
			
			sysUserService.updateById(entity);
			return operateSuccess(model, dwz);
		} catch (Exception e) {
			log.error("保存修改数据出现异常:", e);
			return operateError("保存失败", model);
		}
	}
	
	
	/**
	 * 删除
	 */
//	@RequiresPermissions("pms:role:delete")
	@RequestMapping("/delete")
	public String delete(Model model, Long id, DwzAjax dwz) {
		try {
			SysUser sysUser = sysUserService.selectById(id);
			if (ToolUtil.isEmpty(sysUser)) {
				return operateError("无法获取要删除的数据", model);
			}
			
			//级联删除
			sysUserService.deleteWithCascade(id);
			return operateSuccess(model, dwz);
		} catch (Exception e) {
			log.error("删除出现异常:id="+id, e);
			return operateError("删除失败", model);
		}
	}
	
	
	/**
	 * 转到分配角色页面 .
	 */
//	@RequiresPermissions("pms:role:edit")
	@RequestMapping("/assignRoleUI")
	public String assignRoleUI(Model model, Long id) {
		try {
			SysUser entity = sysUserService.selectById(id);
			if (ToolUtil.isEmpty(entity)) {
				return operateError("获取数据失败", model);
			}
			
			String roleIds = sysUserRoleService.selectRoleIdsByUserId(id);
			List<SysRole> roleList = sysRoleService.selectList(
					new EntityWrapper<SysRole>().eq("delFlag", 0)
					.orderBy("createTime", true)
					);
			
			if(ToolUtil.isNotEmpty(roleIds) && ToolUtil.isNotEmpty(roleList)){
				for(SysRole r: roleList){
					if(roleIds.indexOf(r.getId()+"")>-1){
						r.setStatus(1);
					}else{
						r.setStatus(0);
					}
				}
			}
			model.addAttribute("roleList", roleList);
			
			model.addAttribute("entity",entity);
			return basePagePath+"assignRole";
		} catch (Exception e) {
			log.error("进入编辑页面时，获取数据出现异常:id="+id, e);
			return operateError("获取数据失败", model);
		}
	}
	
	/**
	 * 保存角色分配.
	 */
	@RequestMapping("/assignRole")
	public String assignRole(Model model, Long id, String selectVal, DwzAjax dwz) {
		try {
			SysUser sysUser = sysUserService.selectById(id);
			if (ToolUtil.isEmpty(sysUser)) {
				return operateError("无法获取要删除的数据", model);
			}
			SessionUser su = WebUtil.getSessionUser(request);
			sysUserRoleService.updateByUserId(id,selectVal,su);
			
			return operateSuccess(model, dwz);
		} catch (Exception e) {
			log.error("保存角色分配出现异常:id="+id, e);
			return operateError("保存角色分配失败", model);
		}
	}
}
